package cn.matrix42.potoo.format.json.parser;

import cn.matrix42.potoo.annotation.Public;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Public
public class JsonArray extends JsonNode implements Iterable<JsonNode> {

    private final List<JsonNode> list = new ArrayList<>();

    public JsonArray() {
    }

    @Override
    public boolean isJsonObject() {
        return false;
    }

    @Override
    public boolean isJsonArray() {
        return true;
    }

    @Override
    public boolean isJsonLiteral() {
        return false;
    }

    @Override
    public boolean isNull() {
        return false;
    }

    @Override
    protected String toNormalJson() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i).toNormalJson());
            if (i < list.size() - 1) {
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }

    @Override
    protected String toPrettyJson(int level) {
        StringBuilder sb = new StringBuilder();
        sb.append("[\n");
        for (int i = 0; i < list.size(); i++) {
            sb.append(align(level));
            sb.append(list.get(i).toPrettyJson(level + 1));
            if (i < list.size() - 1) {
                sb.append(",\n");
            }
        }
        if (!list.isEmpty()) {
            sb.append("\n");
            sb.append(align(level - 1));
        }
        sb.append("]");
        return sb.toString();
    }

    @Override
    public ObjectType getObjectType() {
        return ObjectType.JSON_ARRAY;
    }

    @Override
    public Iterator<JsonNode> iterator() {
        return list.iterator();
    }

    public JsonArray add(JsonLiteral jsonLiteral) {
        addInternal(jsonLiteral);
        return this;
    }

    public JsonArray add(JsonArray jsonArray) {
        addInternal(jsonArray);
        return this;
    }

    public JsonArray add(JsonObject jsonObject) {
        addInternal(jsonObject);
        return this;
    }

    private void addInternal(JsonNode jsonNode) {
        if (jsonNode != null && jsonNode.getObjectType() != getObjectType()) {
            throw new IllegalArgumentException();
        }
        list.add(jsonNode);
    }

    public JsonNode get(int index) {
        return list.get(index);
    }

}
